<?php
/**
 * Created by Yury Patrin.
 * Time: 18.06.13 17:08
 */

class Parser
{
    protected $_config;
    protected $_data;

    public function setConfig($config)
    {
        $this->_config = $config;
    }

    public function parse($startPage = 1, $maxPages = 1591)
    {
        $this->_data['clients'] = array();

        for($page = $startPage; $page <= $maxPages; $page++)
        {
            print "Parsing page {$page} \ {$maxPages} ... ";
            $this->_loadPage($page)->getInfo();
            print "  [OK]\n";
        }

        return $this;
    }

    public function saveAsXls($xlsName)
    {
        print "Saving... ";

        if (!is_array($this->_data['clients']))
            return false;

        $xls = new PHPExcel();
        $xls->getProperties()->setCreator("Parser")
            ->setLastModifiedBy("Parser")
            ->setTitle("Customers DB")
            ->setSubject("Customers DB")
            ->setDescription("Customers DB")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("parser");

        $xls->setActiveSheetIndex(0)
            ->setCellValue('A1', '№')
            ->setCellValue('B1', 'Заказчик')
            ->setCellValue('C1', 'Проведено тендеров')
            ->setCellValue('D1', 'Сумма контрактов')
            ->setCellValue('E1', 'ОКПОУ')
            ->setCellValue('F1', 'Адрес');

        $activeSheet = $xls->getActiveSheet();
        $activeSheet
            ->getStyle('A1:F1')
            ->getAlignment()
            ->setWrapText(true)
            ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
            ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
        ;

        $default_border = array( 'style' => PHPExcel_Style_Border::BORDER_MEDIUM, 'color' => array('rgb'=>'d7d2c3') );
        $style_header = array(
            'borders' => array(
                'bottom' => $default_border,
                'left' => $default_border,
                'top' => $default_border,
                'right' => $default_border,
            ),
            'fill' => array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb'=>'faf0e6'),
            ),
            'font' => array(
                'bold' => true,
            )
        );

        $style_color = array(
            'borders' => array(
                'bottom' => $default_border,
                'left' => $default_border,
                'top' => $default_border,
                'right' => $default_border,
            ),
            'fill' => array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb'=>'f5f5dc'),
            ),
            'font' => array(
                'bold' => true,
            )
        );

        $style_nocolor = array(
            'borders' => array(
                'bottom' => $default_border,
                'left' => $default_border,
                'top' => $default_border,
                'right' => $default_border,
            ),
            'fill' => array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('rgb'=>'ffffff'),
            ),
            'font' => array(
                'bold' => true,
            )
        );

        $activeSheet->getStyle('A1')->applyFromArray( $style_header );
        $activeSheet->getStyle('B1')->applyFromArray( $style_header );
        $activeSheet->getStyle('C1')->applyFromArray( $style_header );
        $activeSheet->getStyle('D1')->applyFromArray( $style_header );
        $activeSheet->getStyle('E1')->applyFromArray( $style_header );
        $activeSheet->getStyle('F1')->applyFromArray( $style_header );

        $activeSheet->getColumnDimension('A')->setWidth(10);
        $activeSheet->getColumnDimension('B')->setWidth(55);
        $activeSheet->getColumnDimension('C')->setWidth(13);
        $activeSheet->getColumnDimension('D')->setWidth(15);
        $activeSheet->getColumnDimension('E')->setWidth(15);
        $activeSheet->getColumnDimension('F')->setWidth(75);

        $cell = 2;

        foreach($this->_data['clients'] as $client)
        {
            $xls->setActiveSheetIndex(0)
                ->setCellValue('A'.$cell, $client['Num'])
                ->setCellValue('B'.$cell, $this->_winToUtf8($client['Name']))
                ->setCellValue('C'.$cell, $client['Tenders'])
                ->setCellValue('D'.$cell, $client['Contracts'])
                ->setCellValue('E'.$cell, $client['OKPOU'])
                ->setCellValue('F'.$cell, $this->_winToUtf8($client['Address']))
            ;

            $activeSheet
                ->getStyle('A'.$cell)
                ->getAlignment()
                ->setWrapText(true)
                ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
                ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ;

            $activeSheet
                ->getStyle('C'.$cell)
                ->getAlignment()
                ->setWrapText(true)
                ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
                ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ;

            $activeSheet
                ->getStyle('D'.$cell)
                ->getAlignment()
                ->setWrapText(true)
                ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
                ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ;

            $activeSheet
                ->getStyle('E'.$cell)
                ->getAlignment()
                ->setWrapText(true)
                ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
                ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ;

            $cell++;
        }

        $objWriter = PHPExcel_IOFactory::createWriter($xls, 'Excel2007');
        $objWriter->save($xlsName);

        print "[OK]\n";
    }

    protected function _loadPage($page = 1)
    {
        $html = file_get_contents("http://www.ua-tenders.com/customers/?page={$page}&Search=");
        $html = iconv(mb_detect_encoding($html, mb_detect_order(), true), "UTF-8", $html);
        $this->_data['html'] = $html;

        return $this;
    }

    protected function getInfo()
    {
        if (!$this->_data['html'])
            return false;

        $dom = new domDocument();

        $dom->loadHTML($this->_data['html']);
        $dom->preserveWhiteSpace = false;

        $tenders = $dom->getElementById('tender-table');
        $rows = $tenders->getElementsByTagName('tr');

        foreach ($rows as $row)
        {
            if ($row->getElementsByTagName('td'))
            {
                $cols = $row->getElementsByTagName('td');
                $client = array(
                    'link'      => $this->_getNodeLink($cols->item(1)),
                    'Num'       => trim($cols->item(0)->nodeValue),
                    'Name'      => trim($cols->item(1)->nodeValue),
                    'Tenders'   => trim($cols->item(2)->nodeValue),
                    'Contracts' => trim($cols->item(3)->nodeValue),
                );

                $client = $this->_convert($client);

                if ($client['link'] != false)
                {
                    $additionalInfo = $this->_getAdditionalInfo($client['link']);

                    $additionalInfo['Address'] = strip_tags($additionalInfo['Address']);
                    $additionalInfo['Address'] = str_replace("Контактные данные:","", $additionalInfo['Address']);

                    $additionalInfo = $this->_convert($additionalInfo);

                    $client['Address']  = trim(strip_tags($additionalInfo['Address']));
                    $client['OKPOU']    = trim(strip_tags($additionalInfo['OKPOU']));

                    $this->_data['clients'][] = $client;
                }
            }
        }

        unset($dom);
    }

    protected function _getAdditionalInfo($link)
    {
        $html = file_get_contents($link);

        $dom = new domDocument();

        $dom->loadHTML($html);
        $dom->preserveWhiteSpace = false;

        $content = $dom->getElementById('content');

        $info = $content
            ->getElementsByTagName('div')
            ->item(0)
            ->getElementsByTagName('table')
            ->item(0)
            ->getElementsByTagName('tr')
            ->item(0)
            ->getElementsByTagName('td')
            ->item(1)
            ->nodeValue
        ;

        preg_match_all("/Код ОКПОУ: (\d+)/", $info, $m);
        $okpou = $m[1][0];

        $address = $content
                        ->getElementsByTagName('div')
                        ->item(0)
                        ->getElementsByTagName('table')
                        ->item(0)
                        ->getElementsByTagName('tr')
                        ->item(1)
                        ->getElementsByTagName('td')
                        ->item(0)
                        ->nodeValue
        ;

        return array('Address' => $address, 'OKPOU' => $okpou);
    }

    private function _convert($arr)
    {
        foreach($arr as $key => $val)
        {
            $arr[$key] = iconv(mb_detect_encoding($arr[$key], mb_detect_order(), true), "windows-1251", $arr[$key]);
        }

        return $arr;
    }

    private function _winToUtf8($str)
    {
        return iconv("windows-1251", "UTF-8", $str);
    }

    private function _getNodeLink( $node )
    {
        $innerHTML= '';
        $children = $node->childNodes;

        foreach ($children as $child)
            $innerHTML .= $child->ownerDocument->saveXML( $child );

        preg_match_all('/href="([^"]*)"/', $innerHTML, $links);

        if (isset($links[1]))
        {
            return $links[1][0];
        }
        else
        {
            return false;
        }
    }
}